package jgl.vajra.kingkong.manager;

import android.text.TextUtils;
import android.util.SparseArray;


import jgl.vajra.kingkong.widget.retrofithelper.rxschedulers.RxSchedulersHelper;
import jgl.vajra.kingkong.widget.retrofithelper.rxsubscriber.CommonObserver;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadConnectListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.filedownloader.util.FileDownloadHelper;
import com.liulishuo.filedownloader.util.FileDownloadUtils;

import androidx.databinding.ViewDataBinding;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

import static com.liulishuo.filedownloader.util.FileDownloadUtils.formatString;

public class DownloadTasksManager {


    private final static class HolderClass {
        private final static DownloadTasksManager INSTANCE
                = new DownloadTasksManager();
    }

    public static DownloadTasksManager getInstance() {
        return HolderClass.INSTANCE;
    }


    private DownloadTasksManager() {

    }


    private SparseArray<BaseDownloadTask> taskSparseArray = new SparseArray<>();

    public void addTaskForViewHolder(final BaseDownloadTask task) {
        taskSparseArray.put(task.getId(), task);
    }

    public void removeTaskForViewHolder(final int id) {
        taskSparseArray.remove(id);
    }


    public void releaseTask() {
        taskSparseArray.clear();
    }


    private void registerServiceConnectionListener(FileDownloadConnectListener listener) {
        if (listener != null) {
            FileDownloader.getImpl().removeServiceConnectListener(listener);
        }


        FileDownloader.getImpl().addServiceConnectListener(listener);
    }

    private void unregisterServiceConnectionListener(FileDownloadConnectListener listener) {
        FileDownloader.getImpl().removeServiceConnectListener(listener);
    }

    public void onCreate(FileDownloadConnectListener listener) {

        FileDownloader.getImpl().bindService();
        registerServiceConnectionListener(listener);

    }

    public void onDestroy(FileDownloadConnectListener listener) {
        unregisterServiceConnectionListener(listener);
        releaseTask();
    }

    public boolean isReady() {
        return FileDownloader.getImpl().isServiceConnected();
    }


    /**
     * @param status Download Status
     * @return has already downloaded
     * @see FileDownloadStatus
     */
    public boolean isDownloaded(final int status) {
        return status == FileDownloadStatus.completed;
    }

    public int getStatus(final int id, String path) {
        return FileDownloader.getImpl().getStatus(id, path);
    }

    public long getTotal(final int id) {
        return FileDownloader.getImpl().getTotal(id);
    }

    public long getSoFar(final int id) {
        return FileDownloader.getImpl().getSoFar(id);
    }


    public String createTask(final String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }

        return FileDownloadUtils.getDefaultSaveFilePath(url);
    }

    public void updateViewHolder(final int id, final ViewDataBinding holder) {
        final BaseDownloadTask task = taskSparseArray.get(id);
        if (task == null) {
            return;
        }

        task.setTag(holder);
    }



    public void addDownloadInfoFromDB(long bookId, long sonCatalogsId, String taskPath, int taskId, String url, int downloadStatus) {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
              /*  DownloadChapterBean DownloadChapterBean = new DownloadChapterBean();
                DownloadChapterBean.downloadTaskId = taskId;
                DownloadChapterBean.bookId = bookId;
                DownloadChapterBean.downloadTaskPath = taskPath;
                DownloadChapterBean.sonCategoryId = sonCatalogsId;
                DownloadChapterBean.downloadStatus = downloadStatus;
                DownloadChapterBean.downloadUrl = url;
                DownloadChapterBean.userId = AccountManager.getInstance().getUserId();
                BaseApplication.getDaoSession().getDownloadVideoBeanDao().insertOrReplace(DownloadChapterBean);*/
            }
        }).compose(RxSchedulersHelper.applyIoTransformer()).subscribe(new CommonObserver() {

        });

    }



    public void deleteDownloadInfoFromDB(long bookId, long sonCategoryId) {

        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
               /* DownloadChapterBean DownloadChapterBean = new DownloadChapterBean();
                DownloadChapterBean.userId = AccountManager.getInstance().getUserId();
                DownloadChapterBean.sonCategoryId = sonCategoryId;
                BaseApplication.getDaoSession().getDownloadVideoBeanDao().queryBuilder().where(DownloadVideoBeanDao.Properties.SonCategoryId.eq(sonCategoryId), DownloadVideoBeanDao.Properties.UserId.eq(AccountManager.getInstance().getUserId()), DownloadVideoBeanDao.Properties.BookId.eq(bookId)).buildDelete();
*/            }
        }).compose(RxSchedulersHelper.applyIoTransformer()).subscribe(new CommonObserver() {

        });

    }

    public void editDownloadStatusFromDB(long bookId, long sonCategoryId, int status) {

        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
               /* DownloadChapterBean downloadInfoFromDB = getDownloadInfoFromDB(bookId, sonCategoryId);
                downloadInfoFromDB.downloadStatus = status;
                BaseApplication.getDaoSession().getDownloadVideoBeanDao().update(downloadInfoFromDB);
*/
            }
        }).compose(RxSchedulersHelper.applyIoTransformer()).subscribe(new CommonObserver() {

        });

    }





    public static class VideoDownloadIdGenerator implements FileDownloadHelper.IdGenerator {

        @Override
        public int transOldId(int oldId, String url, String path, boolean pathAsDirectory) {
            return generateId(url, path, pathAsDirectory);
        }

        @Override
        public int generateId(String url, String path, boolean pathAsDirectory) {
            int i = url.indexOf("?");
            if (i>=0) {
                String substring = url.substring(0, i);
                if (pathAsDirectory) {
                    return FileDownloadUtils.md5(formatString("%sp%s@dir", substring, path)).hashCode();
                } else {
                    return FileDownloadUtils.md5(formatString("%sp%s", substring, path)).hashCode();
                }
            }else {
                return FileDownloadUtils.md5(formatString("%sp%s@dir", url, path)).hashCode();
            }
        }
    }

 }
